<?php

namespace addons\shopro\job\trade;

use addons\shopro\job\BaseJob;
use think\queue\Job;
use think\Db;
use think\Log;
use think\exception\HttpResponseException;
use app\admin\model\shopro\trade\Order;
use app\admin\model\shopro\user\User;
use addons\shopro\service\Wallet as WalletService;
use addons\shopro\traits\CouponSend;
use app\admin\model\shopro\Coupon;
use app\admin\model\shopro\user\Coupon as UserCouponModel;

/**
 * 订单自动操作
 */
class OrderPaid extends BaseJob
{

    /**
     * 交易订单支付完成
     */
    public function paid(Job $job, $data)
    {
		$file='./testapi.txt';
		file_put_contents($file,date('Y-m-d H:i:s')."----进入支付成功\n",FILE_APPEND);
        try {
            $order = $data['order'];
            $user = $data['user'];

            $order = Order::where('id', $order['id'])->find();
            $user = User::get($user['id']);
			
			// file_put_contents($file,date('Y-m-d H:i:s').'----'.json_encode($order)."<br>",FILE_APPEND);
			// file_put_contents($file,date('Y-m-d H:i:s').'----'.json_encode($user)."<br>",FILE_APPEND);

			// Log::write('pay-notify-huidiao:');
            // 数据库删订单的问题常见，这里被删的订单直接把队列移除
            if ($order) {
                Db::transaction(function () use ($order, $user, $data) {
					/* if($order->type=="vip"){
						$ext = $order->ext;
						$rule = $ext['rule'] ?? [];
						// $user=auth_user();
						$cids = explode(',',$rule['coupon_ids']);
						foreach($cids as $id){
							$coupon = Coupon::normal()      // 正常的可以展示的优惠券
								->canGet()      // 在领取时间之内的
								->lock(true)
								->where('id', $id)
								->find();
							if (!$coupon) {
								error_stop('优惠券未找到');
							}
							$this->send($user, $coupon);
						}
						
						$days=$rule['days'];
						file_put_contents($file,date('Y-m-d H:i:s').'----days-'.$days."<br>",FILE_APPEND);
						
						if ($days > 0) {
							$nowdate=$user['vipend'] && $user['vipend']!='0000-00-00'?$user['vipend']:date('Y-m-d');
							$afterdate=date('Y-m-d',strtotime($nowdate)+$days*86400);
							db('user')->update(['id'=>$user['id'],'vipend'=>$afterdate,'updatetime'=>time()]);
						}
					} */
                    if ($order->type == 'recharge') {
                        // 充值
                        $ext = $order->ext;
                        $rule = $ext['rule'] ?? [];
                        $money = (isset($rule['money']) && $rule['money'] > 0) ? $rule['money'] : 0;
                        $gift_type = $rule['gift_type'] ?? 'money';
                        $gift = (isset($rule['gift']) && $rule['gift'] > 0) ? $rule['gift'] : 0;
                        if ($money > 0) {
                            // 增加余额
                            WalletService::change($user, 'money', $money, 'order_recharge', [
                                'order_id' => $order->id,
                                'order_sn' => $order->order_sn,
                                'order_type' => 'trade_order',
                            ]);
                        }

                        if ($gift > 0) {
                            // 充值赠送
                            WalletService::change($user, $gift_type, $gift, 'recharge_gift', [
                                'order_id' => $order->id,
                                'order_sn' => $order->order_sn,
                                'order_type' => 'trade_order',
                            ]);
                        }
                    }
					
                });
            }

            // 删除 job
            $job->delete();
        } catch (HttpResponseException $e) {
            $data = $e->getResponse()->getData();
            $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
            format_log_error($e, 'OrderPaid.paid.HttpResponseException', $message);
        } catch (\Exception $e) {
            format_log_error($e, 'OrderPaid.paid');
        }
    }
    /**
     * 发放优惠券
     *
     * @param array|object $user 发放用户
     * @param array|object $coupon 要发放的优惠券
     * @param integer ucid 关联用户优惠券 //masks 新增 
     * @return array|object
     */
    private function send($user, $coupon, $ucid=0) {
        if ($coupon->get_status == 'cannot_get') {
            error_stop('您已经领取过了');
        }

        if ($coupon->stock <= 0) {
            error_stop('优惠券已经被领完了');
        }

        $coupon->setDec('stock');

        $userCoupon = new UserCouponModel();
        $userCoupon->user_id = $user->id;
        $userCoupon->coupon_id = $coupon->id;
        $userCoupon->use_time = null;
		if($ucid){
			$userCoupon->isact=0;
			$userCoupon->ucid=$ucid;
		}
        $userCoupon->save();

        return $userCoupon;
    }

}
